package com.atguigu.utils;

import java.sql.Connection;
import java.sql.SQLException;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import jdk.internal.dynalink.beans.StaticClass;

public class JDBCUntils {
	private static ComboPooledDataSource dataSource = new ComboPooledDataSource("book_developer");
	
	private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
	
	public static Connection getConn() {
		Connection conn = null;
		try {
			conn = threadLocal.get();
			if(conn == null) {
				conn = dataSource.getConnection();
				//设置手动提交
				conn.setAutoCommit(false);
				threadLocal.set(conn);
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}
	
	/**
	 * 设置提交并关闭
	 * */
	public static void commitAndClose() {
		Connection conn = threadLocal.get();
		if(conn != null) {
			try {
				conn.commit();
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		threadLocal.remove();
	}
	
	/**
	 * 设置回滚并关闭
	 * */
	public static void rollbackAndClose() {
		Connection conn = threadLocal.get();
		if(conn != null) {
			try {
				conn.rollback();
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		threadLocal.remove();
	}
}
